Guava 常用操作示例

本篇采用示例的形式展示Guava的常见工具应用.

Guava集合排序

示例代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
List<Integer> list = Arrays.asList(1, 2, 6, 7, 11, 9, 10, 4);
System.out.println("原始集合:" + list);
// 有空元素放置到最后
System.out.println("自然正序:" + Ordering.natural().nullsLast().sortedCopy(list));
// 按照自然排序然后翻转, 有空元素排到最后
System.out.println("自然逆序:" + Ordering.natural().reverse().nullsLast().sortedCopy(list));
// 获取集合最大元素
System.out.println("最小元素:" + Ordering.natural().max(list));
// 获取集合元素中最大的3个元素
System.out.println("最大元素:" + Ordering.natural().greatestOf(list, 3));
// 获取集合最小元素
System.out.println("最小元素:" + Ordering.natural().min(list));
// 获取集合元素中最小的3个元素
System.out.println("最小元素:" + Ordering.natural().leastOf(list, 3));

执行输出

1
2
3
4
5
6
7
原始集合:[1, 2, 6, 7, 11, 9, 10, 4]
自然正序:[1, 2, 4, 6, 7, 9, 10, 11]
自然逆序:[11, 10, 9, 7, 6, 4, 2, 1]
最小元素:11
最大元素:[11, 10, 9]
最小元素:1
最小元素:[1, 2, 4]

示例代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
public static void main(String[] args) {
List<User> list = Arrays.asList(new User(1, "Abc"), new User(3, "BAb"), new User(2,"zbc"), new User(4,"fac"));
System.out.println("原始集合:" + list);

Ordering<User> natureAgeAscOrdering = Ordering.natural().nullsFirst().onResultOf(new Function<User, Integer>() {
public Integer apply(User input) {
return input.getAge();
}
});
System.out.println("年龄升序:" + natureAgeAscOrdering.sortedCopy(list));

Ordering<User> natureNameAscOrdering = Ordering.natural().nullsFirst().onResultOf(new Function<User, String>() {
public String apply(User input) {
return input.getName();
}
});
System.out.println("姓名升序:" + natureNameAscOrdering.sortedCopy(list));
}

@Data
@NoArgsConstructor
@AllArgsConstructor
public static class User{
private int age;
private String name;

@Override
public String toString() {
return "User{" +
"age=" + age +
", name='" + name + '\'' +
'}';
}
}

执行输出

1
2
3
原始集合:[User{age=1, name='Abc'}, User{age=3, name='BAb'}, User{age=2, name='zbc'}, User{age=4, name='fac'}]
年龄升序:[User{age=1, name='Abc'}, User{age=2, name='zbc'}, User{age=3, name='BAb'}, User{age=4, name='fac'}]
姓名升序:[User{age=1, name='Abc'}, User{age=3, name='BAb'}, User{age=4, name='fac'}, User{age=2, name='zbc'}]

Guava集合过滤&转换

示例代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
List<String> list = Lists.newArrayList("a", "A", "1", "B", "as");
Collection<String> filter = Collections2.filter(list, new Predicate<String>() {
public boolean apply(String s) {
return CharMatcher.JAVA_UPPER_CASE.matchesAllOf(s);
}
});
System.out.println("集合过滤:" + filter);

Collection<String> transform = Collections2.transform(list, new Function<String, String>() {
public String apply(String s) {
return s.toUpperCase();
}
});
System.out.println("集合转换:" + transform);

执行输出

1
2
集合过滤:[A, B]
集合转换:[A, A, 1, B, AS]

Guava集合切分

示例代码

1
2
3
4
5
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7);
List<List<Integer>> segmentList = Lists.partition(list, 4);
for(List<Integer> segment: segmentList){
System.out.println(segment);
}

执行输出

1
2
[1, 2, 3, 4]
[5, 6, 7]

Guava不可变集合

当你不希望修改一个集合类,或者想做一个常量集合类的时候,使用immutable集合类就是一个最佳的编程实践。

示例代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
ImmutableList<Integer> immutableList = ImmutableList.<Integer>builder()
.add(1)
.add(1, 2)
.addAll(Arrays.asList(2, 3, 5, 5, 6))
.build();
System.out.println("immutableList:\t" + immutableList);

ImmutableSet<Integer> immutableSet = ImmutableSet.<Integer>builder()
.add(1)
.add(1, 2)
.addAll(Arrays.asList(2, 3, 5, 5, 6))
.build();
System.out.println("immutableSet:\t" + immutableSet);

Map<Integer, String> map = Maps.newHashMap();
map.put(1, "val1");
map.put(2, "val2");
map.put(2, "val3");
ImmutableMap<Integer, String> immutableMap = ImmutableMap.copyOf(map);
System.out.println("immutableMap:\t" + immutableMap);

执行输出

1
2
3
immutableList:  [1, 1, 2, 2, 3, 5, 5, 6]
immutableSet: [1, 2, 3, 5, 6]
immutableMap: {1=val1, 2=val3}

Guava缓存

示例代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
public static void main(String[] args) {
TestCache testCache = new TestCache();
String cacheKey = testCache.buildKey("dateKey");
System.out.println(testCache.getIfPresent(cacheKey));
System.out.println(testCache.getCache(cacheKey));
testCache.putCache(cacheKey, Arrays.asList(1L,2L,3L,4L,5L));
System.out.println(testCache.getIfPresent(cacheKey));
System.out.println(testCache.getCache(cacheKey));
}

static class TestCache {

public static LoadingCache<String, List<Long>> loadingCache = null;

public TestCache(){
init();
}

public void init(){
loadingCache = CacheBuilder.newBuilder()
.expireAfterWrite(5, TimeUnit.MINUTES) // 5分钟自动过期
.build(new CacheLoader<String, List<Long>>() {
@Override
public List<Long> load(String key) throws Exception {
return Lists.newArrayList(); // 默认数据不存在的获取方法
}
});
}

//获取数据,如果不存在返回null
public List<Long> getIfPresent(String key){
return loadingCache.getIfPresent(key);
}

//获取数据,如果数据不存在则通过cacheLoader获取数据,缓存并返回
public List<Long> getCache(String key){
try {
return loadingCache.get(key);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

//直接向缓存put数据
public void putCache(String key, List<Long> value){
if(CollectionUtils.isEmpty(value)){
return;
}
loadingCache.put(key, value);
}

// 构建缓存Key
public String buildKey(String cacheKey){
return cacheKey;
}
}

执行输出

1
2
3
4
null
[]
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]